<template>
  <div class="selfCheckScrapRecord zy-content">
    <!-- 搜索区域（改为直接使用Form） -->
    <!-- 搜索区域（改为使用Row和Col布局） -->
    <div class="search clear">
      <div class="search-box-layout">
        <Row :gutter="24">
          <Col span="4">
            <p class="label">物料编码</p>
            <div class="ipt">
              <Input v-model="searchParams.materialCode" placeholder="请输入物料编码" clearable/>
            </div>
          </Col>
          <Col span="4">
            <p class="label">物料名称</p>
            <div class="ipt">
              <Input v-model="searchParams.materialName" placeholder="请输入物料名称" clearable/>
            </div>
          </Col>
          <Col span="4">
            <p class="label">客户物料号</p>
            <div class="ipt">
              <Input v-model="searchParams.customMaterialCode" placeholder="请输入客户物料号" clearable/>
            </div>
          </Col>
          <Col span="4">
            <p class="label">卷号</p>
            <div class="ipt">
              <Input v-model="searchParams.rollNumber" placeholder="请输入卷号" clearable/>
            </div>
          </Col>
          <Col span="4">
            <p class="label">料位</p>
            <div class="ipt">
              <Input v-model="searchParams.materialLevel" placeholder="请输入料位" clearable/>
            </div>
          </Col>
          <Col span="4">
            <p class="label">箱码</p>
            <div class="ipt">
              <Input v-model="searchParams.boxCode" placeholder="请输入箱码" clearable/>
            </div>
          </Col>
          <div>
            <Col :span="4">
              <div>
                <p class="label hide-label">--</p>
                <div class="ipt">
                  <Button type="primary" class="search-btn" @click="handleSearch">搜索</Button>
                  <Button class="reset-btn" @click="resetSearch">重置</Button>
                </div>
              </div>
            </Col>
          </div>
        </Row>
      </div>
    </div>

    <!-- 操作按钮区域 -->
    <div class="list-layout mt16">
      <div class="btns clear">
        <span class="title">{{ $t("common.listInformation") }}</span>
<!--        <Button @click="showAddModal" style="color: #fff!important;">新增</Button>-->
        <Button @click="exportData">{{ $t("common.Export") }}</Button>
      </div>

      <!-- 表格区域 -->
      <div class="tableContent">
        <Table
            class="resizable-table"
            border
            @on-column-width-resize="onColumnWidthResize"
            :columns="columns"
            ellipsis
            ref="selection"
            stripe
            :data="tableData"
            @on-selection-change="onSelectChange"
        >
          <template slot-scope="{ row }" slot="action">
            <span class="operationBtn" @click="showDetail(row)"><i class="iconfont zy-common-chakan"
                                                                  ></i>详情</span>
            <span class="operationBtn" @click="delRow(row)"><i class="iconfont zy-common-shanchu"
                                                               ></i>{{
                $t('common.Delete')
              }}</span>
          </template>
        </Table>
      </div>

      <!-- 分页 -->
      <div class="pageWrap mt16">
        <pageLeftTitle :total="total" :selected="selectedIds.length"/>
        <Page
            :total="total"
            :page-size="pageSize"
            :page-size-opts="pageSizeOption"
            :current="pageNum"
            @on-change="changePageNum"
            @on-page-size-change="changePageSize"
            show-sizer
            show-total
        />
      </div>
    </div>

    <!-- 新增/编辑模态框 -->
    <Modal
        v-model="modalVisible"
        :title="modalTitle"
        width="800"
        @on-cancel="resetForm"
    >
      <Form ref="form" :model="formData" :rules="formRules" :label-width="120">
        <Row :gutter="16">
          <Col span="12">
            <FormItem label="箱码" prop="boxCode">
              <Input v-model="formData.boxCode" placeholder="请输入箱码"/>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="物料编码" prop="materialCode">
              <Select
                  v-model="formData.materialCode"
                  filterable
                  clearable
                  :remote-method="handleRemote"
                  placeholder="请输入物料编号"
              >
                <Option
                    v-for="item in numberList"
                    :value="item.materialCode"
                    :key="item.materialCode"
                >{{ item.materialCode + ' - ' + item.materialName }}
                </Option>
              </Select>
            </FormItem>
          </Col>

          <Col span="12">
            <FormItem label="料位" prop="materialLevel">
              <Input v-model="formData.materialLevel" placeholder="请输入料位"/>
            </FormItem>
          </Col>

          <Col span="12">
            <FormItem label="卷号" prop="rollNumber">
              <Input v-model="formData.rollNumber" placeholder="请输入卷号"/>
            </FormItem>
          </Col>
          <Col span="12">
            <FormItem label="提报方式" prop="reportingMethod">
              <Select v-model="formData.reportingMethod" placeholder="请选择提报方式">
                <Option value="按数量">按数量</Option>
                <Option value="按重量">按重量</Option>
              </Select>
            </FormItem>
          </Col>

          <Col span="12">
            <FormItem label="班次日期" prop="shiftDate">
              <DatePicker
                  type="date"
                  v-model="formData.shiftDate"
                  placeholder="请选择班次日期"
                  style="width: 100%"
              ></DatePicker>
            </FormItem>
          </Col>
<!--          <Col span="12">-->
<!--            <FormItem label="班次" required>-->
<!--              <Select v-model="formData.shiftId" placeholder="请选择班次">-->
<!--                <Option v-for="shift in shiftList" :key="shift.id" :value="shift.id">-->
<!--                  {{ shift.factoryName }} - {{ shift.shift }}-->
<!--                </Option>-->
<!--              </Select>-->
<!--            </FormItem>-->
<!--          </Col>-->

          <!-- 新增的条料标签字段 -->
          <Col span="12">
            <FormItem label="条料标签" prop="stripLabel">
              <Input
                  v-model="formData.stripLabel"
                  placeholder="请输入或扫描条料标签"
                  style="width: 70%"
              />
              <Button
                  type="primary"
                  style="margin-left: 10px;"
                  @click="handleStripLabelScan"
              >查询
              </Button>
            </FormItem>
          </Col>
        </Row>

        <FormItem label="件码列表" prop="itemCodes">
          <div class="item-code-container">
            <div v-for="(item, index) in formData.itemCodes" :key="index" class="item-code-row">
              <Input
                  v-model="formData.itemCodes[index]"
                  placeholder="请输入件码"
                  style="width: 85%; margin-right: 10px;"
              />
              <Button
                  v-if="index === 0"
                  type="primary"
                  icon="md-add"
                  @click="addItemCode"
                  style="margin-right: 5px;"
              ></Button>
              <Button
                  v-if="index > 0"
                  type="error"
                  icon="md-remove"
                  @click="removeItemCode(index)"
              ></Button>
            </div>
          </div>
          <div v-if="itemCodeError" style="color: #ed4014; margin-top: 5px;">{{ itemCodeError }}</div>
        </FormItem>
      </Form>

      <div slot="footer">
        <Button @click="modalVisible = false">{{ $t("common.Cancel") }}</Button>
        <Button type="primary" @click="submitForm" :loading="submitLoading">
          确认
        </Button>
      </div>
    </Modal>

    <!-- 删除确认弹框 -->
    <Modal :mask-closable="false" v-model="deleteShow" :title="$t('common.Delete')" class="modal-title-layout">
      <div class="icon red">
        <i class="iconfont zy-common-shanchu"></i>
      </div>
      <p class="title">
        <span>{{ $t('common.sureDelete') }}</span>
      </p>
      <div slot="footer">
        <Button type="default" @click="deleteShow = false">{{ $t('common.Cancle') }}</Button>
        <Button type="primary" @click="deleteSure">{{ $t('maintenance.Confirmed') }}</Button>
      </div>
    </Modal>

    <!-- 件码详情弹框 -->
    <Modal v-model="detailVisible" title="件码详情" width="600">
      <Table :columns="detailColumns" :data="detailData" border></Table>
      <div slot="footer">
        <Button type="primary" @click="detailVisible = false">关闭</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import fileDownload from "js-file-download";

export default {
  name: "boxItemCodeBinding",
  data() {
    return {
      numberList: [],
      itemCodeError: '',
      deleteShow: false,
      detailVisible: false,
      currentDeleteId: null,
      currentDetailId: null,
      // 搜索相关
      searchParams: {
        materialCode: '',
        materialName: '',
        customMaterialCode: '',
        rollNumber: '',
        materialLevel: '',
        boxCode: ''
      },

      // 表格相关
      columns: [
        {type: "selection", width: 60, align: "center"},
        {title: "物料编码", key: "materialCode", minWidth: 150, align: "center"},
        {title: "物料名称", key: "materialName", minWidth: 150, align: "center"},
        {title: "客户物料号", key: "customMaterialCode", minWidth: 150, align: "center"},
        {title: "卷号", key: "rollNumber", minWidth: 120, align: "center"},
        {title: "料位", key: "materialLevel", minWidth: 120, align: "center"},
        {title: "箱码", key: "boxCode", minWidth: 120, align: "center"},
        {title: "绑定日期", key: "shiftDate", minWidth: 120, align: "center"},
        // {title: "班次", key: "shiftName", minWidth: 120, align: "center"},
        {
          title: "操作",
          slot: "action",
          fixed: "right",
          width: 180,
          align: "center"
        }
      ],
      tableData: [],
      total: 0,
      pageNum: 1,
      pageSize: 10,
      pageSizeOption: [10, 20, 30, 50],
      selectedIds: [],

      // 详情表格列
      detailColumns: [
        {title: "序号", type: "index", width: 80, align: "center"},
        {title: "件码", key: "itemCode", align: "center"},
        {title: "扫码时间", key: "scanDateTime", align: "center"},
      ],
      detailData: [],

      // 表单相关
      modalVisible: false,
      modalTitle: "新增箱码绑定",
      submitLoading: false,
      isEdit: false,
      currentId: null,

      // 班次列表
      shiftList: [],
      formData: {
        boxCode: "",
        materialCode: "",
        customMaterialCode: "",
        materialLevel: "",
        rollNumber: "",
        reportingMethod: "按数量",
        shiftDate: "",
        shiftId: "",
        shiftName: "",
        stripLabel: "", // 新增的条料标签字段
        itemCodes: [""] // 初始化为一个空字符串的数组
      },
      formRules: {
        boxCode: [
          {required: true, message: "请输入箱码", trigger: "blur"}
        ],
        materialCode: [
          {required: true, message: "请选择物料编码", trigger: "change"}
        ],
        customMaterialCode: [
          {required: true, message: "请输入客户物料号", trigger: "blur"}
        ],
        materialLevel: [
          {required: true, message: "请输入料位", trigger: "blur"}
        ],
        rollNumber: [
          {required: true, message: "请输入卷号", trigger: "blur"}
        ],
        reportingMethod: [
          {required: true, message: "请选择提报方式", trigger: "change"}
        ],
        shiftDate: [
          {required: true, type: 'date', message: "请选择班次日期", trigger: "change"}
        ],
      }
    };
  },

  mounted() {
    this.getList();
    this.handleRemote('');
    this.getOption();
  },

  methods: {
    // 判断字符串是否以某个字符串开头
    startsWith(str, prefix) {
      return new RegExp(`^${prefix}`).test(str);
    },

    // 处理条料标签扫码查询
    async handleStripLabelScan() {
      const code = this.formData.stripLabel.trim();
      if (!code) {
        this.$Message.error("请输入或扫描条料标签");
        return;
      }

      try {
        if (this.startsWith(code, "TAG")) {
          // TAG开头的标签处理
          const response = await this.axios({
            method: "post",
            url: "/dms/apiMethod/outboundLabelInfo",
            data: {serialNo: code}
          });

          if (response.code === 1 && response.data && response.data.length > 0) {
            this.formData.materialCode = response.data[0].materialCode;
            this.formData.rollNumber = response.data[0].batchProp.prop_JH || "";
            this.formData.materialLevel = ""; // TAG标签不带料位
            this.$Message.success("标签信息获取成功");
          } else {
            this.$Message.error(response.message || "获取TAG标签信息失败");
          }
        } else if (this.startsWith(code, "scene_01")) {
          // scene_01开头的标签处理
          const tagSerial = code.replace("scene_01;", "");
          const response = await this.axios({
            method: "get",
            url: `/dms/labelPrinting/getLabelInfoBySerial?tagSerial=${tagSerial}`
          });

          if (response.code === 200 && response.data) {
            this.formData.materialCode = response.data.materialCode;
            this.formData.rollNumber = response.data.volumeNumber;
            this.formData.materialLevel = response.data.materialLevel;
            this.$Message.success("标签信息获取成功");
          } else {
            this.$Message.error(response.message || "获取scene_01标签信息失败");
          }
        } else {
          this.$Message.error("不支持的标签格式");
        }
      } catch (error) {
        console.error("条料标签查询失败:", error);
        this.$Message.error("条料标签查询异常");
      }
    },

    getOption() {
      this.axios({
        method: 'POST',
        url: '/dms/productionShift/page',
        data: {
          pageNum: 1,
          pageSize: 999
        }
      }).then(res => {
        if (res.code === 200) {
          this.shiftList = res.data.records;
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      });
    },

    handleRemote(query) {
      this.axios({
        method: 'POST',
        url: '/dms/material/page',
        data: {
          materialCode: query,
          pageNum: 1,
          pageSize: 20
        }
      }).then(res => {
        if (res.code === 200) {
          this.numberList = res.data.records;
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      });
    },

    // 获取列表数据
    getList() {
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        ...this.searchParams
      };

      this.axios({
        method: "get",
        url: "/dms/boxItemCodeBinding/listPage",
        params
      }).then(res => {
        if (res.code === 200) {
          this.tableData = res.data.list || [];
          this.total = res.data.total || 0;
        }
      });
    },

    // 搜索
    handleSearch() {
      this.pageNum = 1;
      this.getList();
    },

    // 重置搜索
    resetSearch() {
      this.$refs.searchForm.resetFields();
      this.handleSearch();
    },

    // 显示新增模态框
    showAddModal() {
      this.modalTitle = "新增箱码绑定";
      this.isEdit = false;
      this.currentId = null;
      this.modalVisible = true;
    },

    // 显示详情
    showDetail(row) {
      this.detailData = row.itemCodeList;
      this.detailVisible = true;
    },

    // 删除确认
    delRow(row) {
      this.currentDeleteId = row.id;
      this.deleteShow = true;
    },

    // 确认删除
    deleteSure() {
      if (this.currentDeleteId) {
        this.axios({
          method: "delete",
          url: `/dms/boxItemCodeBinding/delete?id=${this.currentDeleteId}`
        }).then(res => {
          if (res.code === 200) {
            this.$Message.success("删除成功");
            this.deleteShow = false;
            this.getList();
          } else {
            this.$Message.error(res.msg || '删除失败');
          }
        }).catch(error => {
          this.$Message.error('删除失败: ' + (error.message || ''));
        });
      }
    },

    // 添加新的件码输入框
    addItemCode() {
      this.formData.itemCodes.push("");
    },

    // 移除件码输入框
    removeItemCode(index) {
      this.formData.itemCodes.splice(index, 1);
      this.itemCodeError = ''; // 清除错误信息
    },

    // 提交表单
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          this.$Message.error('请填写完整表单信息');
          return;
        }

        let hasEmptyItemCode = false;
        const validItemCodes = this.formData.itemCodes.filter(item => {
          if (item.trim() === '') {
            hasEmptyItemCode = true;
          }
          return item.trim() !== '';
        });

        if (hasEmptyItemCode) {
          this.itemCodeError = '件码不能为空';
          this.$Message.error('请填写完整的件码信息');
          return;
        }

        if (validItemCodes.length === 0) {
          this.itemCodeError = '请至少输入一个件码';
          this.$Message.error('请至少输入一个件码');
          return;
        }

        this.itemCodeError = '';
        this.submitLoading = true;

        const formData = {
          ...this.formData,
          shiftDate: this.formData.shiftDate ? new Date(this.formData.shiftDate).toISOString() : null,
          itemCodes: validItemCodes
        };

        const shift = this.shiftList.find(item => item.id === this.formData.shiftId);
        if (shift) {
          formData.shiftName = shift.shift;
        } else {
          formData.shiftName = '';
        }

        const request = this.isEdit
            ? this.axios.put(`/dms/boxItemCodeBinding/update/${this.currentId}`, formData)
            : this.axios.post("/dms/boxItemCodeBinding/add", formData);

        request.then(res => {
          if (res.code === 200) {
            this.$Message.success(this.isEdit ? "修改成功" : "新增成功");
            this.modalVisible = false;
            this.getList();
          } else {
            this.$Message.error(res.msg || '操作失败');
          }
        }).catch(error => {
          this.$Message.error('操作失败: ' + (error.message || ''));
        }).finally(() => {
          this.submitLoading = false;
        });
      });
    },

    // 导出数据
    exportData() {
      const params = {...this.searchParams};

      this.axios({
        method: "get",
        url: "/dms/boxItemCodeBinding/export",
        params,
        responseType: "blob"
      }).then(res => {
        fileDownload(res, `箱码绑定件码.xlsx`);
      }).catch(error => {
        this.$Message.error('导出失败: ' + (error.message || ''));
      });
    },

    // 重置表单
    resetForm() {
      this.$refs.form.resetFields();
      this.formData = {
        boxCode: "",
        materialCode: "",
        customMaterialCode: "",
        materialLevel: "",
        rollNumber: "",
        reportingMethod: "按数量",
        shiftDate: "",
        shiftId: "",
        shiftName: "",
        stripLabel: "", // 重置条料标签字段
        itemCodes: [""]
      };
      this.itemCodeError = '';
    },

    // 分页变化
    changePageNum(val) {
      this.pageNum = val;
      this.getList();
    },

    changePageSize(val) {
      this.pageSize = val;
      this.getList();
    },

    // 表格选择变化
    onSelectChange(selection) {
      this.selectedIds = selection.map(item => item.id);
    },

    // 列宽调整
    onColumnWidthResize(data) {
      // 可以保存列宽设置到本地存储
    }
  }
};
</script>

<style scoped lang="scss">
.boxItemCodeBinding {
  .search-area {
    padding: 16px;
    background: #fff;
    border-radius: 4px;
    margin-bottom: 16px;
    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
  }

  .ivu-form-item {
    margin-bottom: 16px;
  }

  .ivu-col {
    display: flex;
    flex-direction: column;
  }

  .ivu-form-item-content {
    flex: 1;
  }

  .operationBtn {
    margin: 0 5px;
    cursor: pointer;
    color: #2d8cf0;

    &:hover {
      text-decoration: underline;
    }
  }

  .ivu-table-cell {
    padding: 12px 8px;
  }

  .item-code-container {
    width: 100%;

    .item-code-row {
      display: flex;
      align-items: center;
      margin-bottom: 10px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}
</style>